import { ThemeProvider } from "@react-navigation/native";
import { Stack } from "expo-router";
import * as SplashScreen from "expo-splash-screen";
import React, { useEffect } from "react";
import { useLoadedFontFamily } from "@/hooks/font";
import { useColorScheme } from "react-native";
import i18n, { getDeviceLanguage } from "@/constants/i18n";
import "@/assets/styles/global.css";
import "@/constants/i18n";
import { scheduleLocalNotification, setupNotificationListeners, useRegisterForPushNotificationsAsync } from "@/hooks/premise";
import * as Notifications from "expo-notifications";
import { DefaultDarkTheme, DefaultLightTheme } from "@/constants/color";
import { Provider } from "react-redux";
import { store } from "@/stores";
import { StatusBar } from "expo-status-bar";
import { database, useMigrationsDb } from "@/drizzle";

SplashScreen.preventAutoHideAsync();

const RootLayoutNav: React.FC<NavigationProps.NavProps<typeof Stack, keyof typeof NavigationProps.NavigationApp, typeof Stack.Screen>> = ({
  option = { screenOptions: { headerShown: false } },
  items = {
    SYSTEM: { options: { headerShown: false }, name: "(system)" },
    MODAL: { options: { headerShown: false, presentation: "modal" }, name: "(modal)" },
  },
}) => (
  <Provider store={store}>
    <StatusBar style={useColorScheme() == "dark" ? "light" : "dark"} />
    <ThemeProvider value={useColorScheme() == "dark" ? DefaultDarkTheme : DefaultLightTheme}>
      <Stack {...option}>
        {Object.entries(items).map(([key, value]) => (
          <Stack.Screen key={key} {...value} />
        ))}
      </Stack>
    </ThemeProvider>
  </Provider>
);

const RootAppLayout = () => {
  const { Loaded, Error } = useLoadedFontFamily();
  const { error, success } = useMigrationsDb();
  useEffect(() => {
    i18n.changeLanguage(getDeviceLanguage());
    // useRegisterForPushNotificationsAsync();
    // const subscription = Notifications.addNotificationReceivedListener(notification => {
    //   console.log('Notification received:', notification);
    // });
    // scheduleLocalNotification();
    // setupNotificationListeners();
    // return () => subscription.remove();
  }, []);

  useEffect(() => {
    if (Loaded) SplashScreen.hideAsync();
    if (Error) alert(Error);
    if (error) console.log(error.message);
  }, [Loaded, Error, error, success]);

  if (!Loaded) return null;

  return <RootLayoutNav />;
};

export default RootAppLayout;
